<template>
  <div class="wrap-container sn-container">
    <div class="sn-content">
      <div class="sn-body">
        <div class="wrap-container">
          <div v-if="loading" class="loading">
            <div class="spinner"></div>
            <p>正在请求数据...</p>
          </div>
          <div v-else class="chartsdom" id="chart_ptrend"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-gl';
import { getalarmData } from '@/api/echarts';

export default {
  name: "pyramidTrend",
  data() {
    return {
      option: null,
      dataMap: {},
      alarmEquipmentNumber: [],
      faultEquipmentNumbers: [],
      offlineEquipmentNumbers: [],
      months: [],
      loading: true,
      cachedData: null,
      refreshInterval: null // 添加定时器变量
    }
  },
  created() {
    this.fetchData();
  },
  mounted() {
    this.refreshInterval = setInterval(this.fetchData, 864000000); // 设置定时器，10天（864000000 毫秒）刷新一次
    window.addEventListener('resize', this.resizeChart);
  },
  methods: {
    fetchData() {
      // 检查是否有缓存数据
      if (this.cachedData) {
        this.processData(this.cachedData);
        return;
      }

      getalarmData().then(res => {
        this.cachedData = res.msg; // 缓存数据
        this.processData(res.msg);
      }).catch(error => {
        console.error(error);
        this.loading = false;
      });
    },
    processData(data) {
      this.alarmEquipmentNumber = data.map(item => item.alarmEquipmentNumber);
      this.faultEquipmentNumbers = data.map(item => item.faultEquipmentNumber);
      this.offlineEquipmentNumbers = data.map(item => item.offlineEquipmentNumber);
      this.months = data.map(item => `${item.month}月份`);
      this.loading = false;

      this.$nextTick(() => {
        this.initEchart();
      });
    },
    dataFormatter(obj) {
      let pList = ['数值报警设备数量', '故障报警设备数量', '离线报警设备数量'];
      let temp;

      for (let x = 0; x < 3; x++) {
        let max = 0;
        let sum = 0;
        temp = obj[x];
        for (let i = 0, l = temp.length; i < l; i++) {
          max = Math.max(max, temp[i]);
          sum += temp[i];

          obj[x][i] = {
            name: pList[x],
            value: temp[i]
          };
        }

        obj[x + 'max'] = Math.floor(max / 100) * 100;
        obj[x + 'sum'] = sum;
      }

      return obj;
    },
    initEchart() {
      this.$nextTick(() => {
        let chartDom = document.getElementById('chart_ptrend');
        if (!chartDom) return;

        let myChart = echarts.init(chartDom);
        let itemStyle = {
          barBorderRadius: [15, 0],
          color: '#ffe000'
        };

        this.dataMap.dataType = this.dataFormatter({
          0: [
            this.alarmEquipmentNumber[0],
            this.faultEquipmentNumbers[0],
            this.offlineEquipmentNumbers[0],
          ],
          1: [
            this.alarmEquipmentNumber[1],
            this.faultEquipmentNumbers[1],
            this.offlineEquipmentNumbers[1],
          ],
          2: [
            this.alarmEquipmentNumber[2],
            this.faultEquipmentNumbers[2],
            this.offlineEquipmentNumbers[2],
          ],
        });

        this.option = {
          baseOption: {
            timeline: {
              axisType: 'category',
              autoPlay: true,
              playInterval: 2000,
              data: this.months,
              left: 80,
              right: 80,
              bottom: 10,
              lineStyle: {
                color: '#179bf1'
              },
              label: {
                color: '#fff'
              },
              checkpointStyle: {
                color: '#01d8ff',
                symbolSize: 10,
                borderColor: 'rgba(1, 216, 255, 0.5)',
                borderWidth: 5,
              },
              controlStyle: {
                show: false,
              },
              itemStyle: {
                borderColor: '#004b85',
                borderWidth: 1,
                shadowColor: 'rgba(1, 216, 225, 0.5)',
                shadowBlur: 5
              },
              emphasis: {
                label: {
                  color: '#01d8ff',
                  show: false
                },
                checkpointStyle: {
                  color: '#01d8ff',
                  borderColor: 'rgba(1, 216, 255, 0.5)',
                  borderWidth: 5,
                },
                itemStyle: {
                  color: '#01d8ff',
                  borderColor: 'rgba(1, 216, 225, 0.5)',
                  borderWidth: 5
                }
              }
            },
            calculable: true,
            grid: {
              top: '10%',
              bottom: '25%'
            },
            xAxis: [{
              type: 'category',
              axisLabel: {
                interval: 0
              },
              data: ['数值报警设备数量', '故障报警设备数量', '离线报警设备数量'],
              splitLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#ffffff',
                }
              },
            }],
            yAxis: [{
              type: 'value',
              name: '个',
              splitLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#ffffff'
                }
              }
            }],
            series: [{
              name: '一类',
              type: 'bar',
              barWidth: 30,
              legendHoverLink: true,
              label: {
                show: true,
                position: 'top',
                color: '#fff'
              },
            }]
          },
          options: [{
            series: [{
              data: this.dataMap.dataType['0'],
              itemStyle: itemStyle
            }]
          }, {
            series: [{
              data: this.dataMap.dataType['1'],
              itemStyle: itemStyle
            }]
          }, {
            series: [{
              data: this.dataMap.dataType['2'],
              itemStyle: itemStyle
            }]
          }]
        }

        myChart.setOption(this.option, true);

        window.addEventListener('resize', this.resizeChart);
      });
    },
    resizeChart() {
      let chartDom = document.getElementById('chart_ptrend');
      if (chartDom) {
        let myChart = echarts.getInstanceByDom(chartDom);
        if (myChart) {
          myChart.resize();
        }
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.refreshInterval); // 清除定时器
    window.removeEventListener('resize', this.resizeChart);
  }
};
</script>

<style lang="scss" scoped>
.sn-container {
  transform: scale(0.9);
  bottom: -2vh;
  height: 115%;

  .chartsdom {
    width: 100%;
    height: 105%;
  }

  .loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #fff;

    .spinner {
      border: 4px solid rgba(255, 255, 255, 0.3);
      border-left-color: #fff;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      animation: spin 1s linear infinite;
    }
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
}
</style>
